package com.runen.wnhz.runen.ui.activity.main;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioButton;

import com.runen.wnhz.runen.R;
import com.runen.wnhz.runen.common.utils.ACacheUtlis;
import com.runen.wnhz.runen.common.utils.Constants;
import com.runen.wnhz.runen.common.utils.StatusBarCompatUtils;
import com.runen.wnhz.runen.common.utils.ToastUtil;
import com.runen.wnhz.runen.di.component.ApplicationComponent;
import com.runen.wnhz.runen.service.ExampleUtil;
import com.runen.wnhz.runen.ui.RunEnArActivity;
import com.runen.wnhz.runen.ui.activity.BaseActivity;
import com.runen.wnhz.runen.ui.activity.mine.MineFragment;
import com.runen.wnhz.runen.ui.fragment.major.MajorFragment;
import com.runen.wnhz.runen.ui.fragment.minem.HomeFragment;
import com.runen.wnhz.runen.ui.fragment.publicm.PublicFragment;
import com.runen.wnhz.runen.widget.TitleBuilder;

import org.simple.eventbus.Subscriber;

import android.content.Intent;

import butterknife.BindView;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;


public class MainActivity extends BaseActivity implements View.OnClickListener {

    //fragment管理
    FragmentTransaction transaction;
    //四个fragment
    HomeFragment homeFragment;
    MajorFragment majorFragment;
    PublicFragment publicFragment;
    MineFragment mineFragment;
    //当前存在的fragment
    Fragment mCurrentFragment;

    @BindView(R.id.rb_home)
    RadioButton rb_home;
    @BindView(R.id.rb_major)
    RadioButton rb_major;
    @BindView(R.id.rb_public)
    RadioButton rb_public;
    @BindView(R.id.rb_mine)
    RadioButton rb_mine;
    @BindView(R.id.iv_ar)
    ImageView iv_ar;

    public static boolean isForeground = false;

    @Override
    protected int getLayoutView() {
        return R.layout.activity_main;
    }

    @Override
    protected void onTitleClickListen(TitleBuilder.TitleButton clicked) {
        switch (clicked) {
            case LEFT:
                break;
            case MIDDLE:
                break;
            case RIGHT:
                break;
            default:
                break;
        }
    }

    @Override
    protected void initStart() {
        StatusBarCompatUtils.getInstance().TranslucentStatusBar(this, R.color.title_green);
        initLinseter();
        addFragmentToStack(0);
        rb_home.toggle();
        getPushMessage();
        registerMessageReceiver();  // used for receive msg
    }


    @Override
    public void initToolBar(TitleBuilder mTitleBuilder) {
        setToolBarVisible(View.GONE);
    }

    @Override
    public void setupAcitivtyComponent(ApplicationComponent appComponent) {

    }


    private void initLinseter() {

        rb_home.setOnClickListener(this);
        rb_major.setOnClickListener(this);
        rb_public.setOnClickListener(this);
        rb_mine.setOnClickListener(this);
        iv_ar.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rb_home:
                addFragmentToStack(0);
                break;
            case R.id.rb_major:
                addFragmentToStack(1);
                break;
            case R.id.rb_public:
                addFragmentToStack(2);
                break;
            case R.id.rb_mine:
                addFragmentToStack(3);
                break;
            case R.id.iv_ar:
                startActivity(new Intent(MainActivity.this, RunEnArActivity.class));
                break;
            default:
                ToastUtil.showToast("App未知错误");
                break;
        }
    }

    // 切换fragment
    private void addFragmentToStack(int currSel) {
        transaction = getSupportFragmentManager().beginTransaction();
        hideFragment(transaction);
        switch (currSel) {
            case 0:
                if (homeFragment == null) {
                    homeFragment = new HomeFragment();
                    transaction.add(R.id.ll_fragment_container, homeFragment, HomeFragment.TAG);
                } else {
                    transaction.show(homeFragment);
                }
                mCurrentFragment = homeFragment;
                break;
            case 1:
                if (majorFragment == null) {
                    majorFragment = new MajorFragment();
                    transaction.add(R.id.ll_fragment_container, majorFragment, MajorFragment.TAG);
                } else {
                    transaction.show(majorFragment);
                }
                mCurrentFragment = majorFragment;
                break;
            case 2:
                if (publicFragment == null) {
                    publicFragment = new PublicFragment();
                    transaction.add(R.id.ll_fragment_container, publicFragment, PublicFragment.TAG);
                } else {
                    transaction.show(publicFragment);
                }
                mCurrentFragment = publicFragment;
                break;
            case 3:
                if (mineFragment == null) {
                    mineFragment = new MineFragment();
                    transaction.add(R.id.ll_fragment_container, mineFragment, MineFragment.TAG);
                } else {
                    transaction.show(mineFragment);
                }
                mCurrentFragment = mineFragment;
                break;
            default:
                break;
        }

        transaction.commitAllowingStateLoss();

    }

    private void hideFragment(FragmentTransaction transaction) {
        if (homeFragment != null) {
            transaction.hide(homeFragment);
        }
        if (majorFragment != null) {
            transaction.hide(majorFragment);
        }
        if (publicFragment != null) {
            transaction.hide(publicFragment);
        }

        if (mineFragment != null) {
            transaction.hide(mineFragment);
        }
    }

    public void goToFragment(int currSel) {
        transaction = getSupportFragmentManager().beginTransaction();
        hideFragment(transaction);
        addFragmentToStack(currSel);
    }

    @Subscriber(tag = "rbSelected")
    public void selectRb(int id) {
        switch (id) {
            case 0:
                rb_home.toggle();
                break;
            case 1:
                rb_major.toggle();
                break;
            case 2:
                rb_public.toggle();
                break;
            case 3:
                rb_mine.toggle();
                break;
            default:
                break;
        }
    }

    /**
     * 得到不落地 push 消息
     */
    private void getPushMessage() {
        if (!TextUtils.isEmpty(ACacheUtlis.getInstance().isLogin(this))) {
            if (ACacheUtlis.getInstance().isLogin(this).equals("true")) {
                //融云断开连接的时候
                String cacheToken = preferences.getString(Constants.RongIMToken, "");
                if (!RongIM.getInstance().getCurrentConnectionStatus().equals(RongIMClient.ConnectionStatusListener.ConnectionStatus.CONNECTED)) {

                    RongIM.connect(cacheToken, new RongIMClient.ConnectCallback() {
                        @Override
                        public void onTokenIncorrect() {

                        }

                        @Override
                        public void onSuccess(String s) {

                        }

                        @Override
                        public void onError(RongIMClient.ErrorCode e) {

                        }
                    });
                }
            }
        }
    }

    @Override
    protected void onPause() {
     isForeground = false;
        super.onPause();
    }

    //for receive customer msg from jpush server
    private MessageReceiver mMessageReceiver;
    public static final String MESSAGE_RECEIVED_ACTION = "com.example.jpushdemo.MESSAGE_RECEIVED_ACTION";
    public static final String KEY_TITLE = "title";
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_EXTRAS = "extras";
    public void registerMessageReceiver() {
        mMessageReceiver = new MessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(MESSAGE_RECEIVED_ACTION);
        LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, filter);
    }

    public class MessageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
                    String messge = intent.getStringExtra(KEY_MESSAGE);
                    String extras = intent.getStringExtra(KEY_EXTRAS);
                    StringBuilder showMsg = new StringBuilder();
                    showMsg.append(KEY_MESSAGE + " : " + messge + "\n");
                    if (!ExampleUtil.isEmpty(extras)) {
                        showMsg.append(KEY_EXTRAS + " : " + extras + "\n");
                    }
                    setCostomMsg(showMsg.toString());
                }
            } catch (Exception e){
            }
        }



    }


    private void setCostomMsg(String msg){
        if (null != msg) {
            ToastUtil.showToast("接收到当前消息："+ msg);
//            msgText.setText(msg);
//            msgText.setVisibility(android.view.View.VISIBLE);
        }
    }


    @Override
    protected void onResume() {
        isForeground = true;
        super.onResume();
    }
}
